// AppLauncher.java
package com.sion.servicekeep;

import android.app.ActivityManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.os.Handler;
import android.util.Log;

import java.util.Calendar;
import java.util.List;

public class AppLauncher {
    private static final String TAG = "AppLauncher";
    private static final String ACTION_APP_LAUNCHED = "com.sion.servicekeep.ACTION_APP_LAUNCHED"; // 新增广播动作常量
    private Context context;
    private int checkInterval;
    private Handler handler;
    private Runnable checkRunnable;

    private static final int STARTUP_DELAY = 1000; // 1 秒延迟后才能启动

    public AppLauncher(Context context, int checkInterval) {
        this.context = context;
        this.checkInterval = checkInterval;
        this.handler = new Handler();
        this.checkRunnable = new Runnable() {
            @Override
            public void run() {
                // 动态获取 MainActivity 中的 selectedPackageName
                String packageName = MainActivity.selectedPackageName;
                // 检查 packageName 是否为空以及 isDaemonCleared 是否为 false
                if (packageName != null && !packageName.isEmpty() && !((MainActivity) context).isDaemonCleared) {
                    Log.d("APPLauncher","目标应用"+packageName+"   \tisDaemonCleared:"+((MainActivity) context).isDaemonCleared);
                    if (!isAppRunning()) {
                        Log.d("isAppRunning","应用启动，");
                        startApp(packageName);
                    }
                }
                handler.postDelayed(this, checkInterval * 1000);
            }
        };
    }

    public void startMonitoring() {
        handler.postDelayed(() -> {
            handler.postDelayed(checkRunnable, 0);
        }, STARTUP_DELAY);
    }

    public void stopMonitoring() {
        handler.removeCallbacks(checkRunnable);
    }

    private boolean startApp(String packageName) {
        PackageManager packageManager = context.getPackageManager();
        Intent launchIntent = packageManager.getLaunchIntentForPackage(packageName);
        if (launchIntent != null) {
            try {
                context.startActivity(launchIntent);
                Log.d(TAG, "App started successfully: " + packageName);
                // 发送广播通知悬浮窗更新样式
                Intent appLaunchedIntent = new Intent(ACTION_APP_LAUNCHED);
                context.sendBroadcast(appLaunchedIntent);
                return true;
            } catch (Exception e) {
                Log.e(TAG, "Failed to start app: " + e.getMessage());
            }
        }

        // 尝试使用隐式意图启动
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setPackage(packageName);
        List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(intent, 0);
        if (!resolveInfos.isEmpty()) {
            ResolveInfo resolveInfo = resolveInfos.get(0);
            Intent explicitIntent = new Intent(intent);
            explicitIntent.setClassName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name);
            try {
                context.startActivity(explicitIntent);
                Log.d(TAG, "App started successfully using explicit intent: " + packageName);
                // 发送广播通知悬浮窗更新样式
                Intent appLaunchedIntent = new Intent(ACTION_APP_LAUNCHED);
                context.sendBroadcast(appLaunchedIntent);
                return true;
            } catch (Exception e) {
                Log.e(TAG, "Failed to start app using explicit intent: " + e.getMessage());
            }
        }

        return false;
    }

    public boolean isAppRunning() {
        // 动态获取 MainActivity 中的 selectedPackageName
        String packageName = MainActivity.selectedPackageName;
//        Log.d("isAppRunning","进入判断");
        // 首先尝试使用 UsageStatsManager
        if (isAppInForegroundUsingUsageStats(packageName)) {
//            Log.d("UsageStatsManager","UsageStatsManager ok");
            return true;
        }

        // 然后尝试使用 ActivityManager
        if (isAppRunningUsingActivityManager(packageName)) {
            Log.d("ActivityManager","ActivityManager ok");
            return true;
        }

        return false;
    }

    private boolean isAppInForegroundUsingUsageStats(String packageName) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
            Calendar calendar = Calendar.getInstance();
            long endTime = calendar.getTimeInMillis();
            calendar.add(Calendar.YEAR, -1);
            long startTime = calendar.getTimeInMillis();

            List<UsageStats> usageStatsList = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime);
            if (usageStatsList != null && !usageStatsList.isEmpty()) {
                UsageStats recentStats = null;
                for (UsageStats usageStats : usageStatsList) {
                    if (recentStats == null || usageStats.getLastTimeUsed() > recentStats.getLastTimeUsed()) {
                        recentStats = usageStats;
                    }
                }
                if (recentStats != null && recentStats.getPackageName().equals(packageName)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean isAppRunningUsingActivityManager(String packageName) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses != null) {
            for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
                if (appProcess.processName.equals(packageName)) {
                    Log.d(TAG, "AppRunning is true: " + packageName);
                    return true;
                }
            }
        }
        Log.d(TAG, "AppRunning is false: " + packageName);
        return false;
    }
}